<template>
  <div>
    <ylheader :leftsvg="true" :title="'说说详情'" :rightmoresvg="isme" @moresvg="deletemycomment" :isrightcollectsvgshow="!isme" :rightcollectsvg="rightcollectsvgicon" @collectevent="iscollectevent"></ylheader>
    <deletepopup :type="myshenhetype" @candelete="deletetopiccomments" @cancledelete="canaledeteletopiccomments" :isshowdeletepopup="showdelete"  @deleteshow="deleteshow"></deletepopup>
    <mt-popup
      v-model="isdelete" position="bottom">
      <div style="width: 7.5rem;display: flex;flex-direction: column;align-items: center">
        <div class="delete" @click="deletemycomments">
          <span>删除</span>
        </div>
        <div style="background-color: #f5f5f5;height: 0.1rem;width: 100%"></div>
        <div @click="iscancle" class="cancle" >
          <span>取消</span>
        </div>
      </div>
    </mt-popup>

    <mt-popup
      v-model="isreply" position="bottom">
      <div style="width: 7.5rem;display: flex;flex-direction: column;align-items: center">
        <div class="delete" @click="replycom">
          <span>回复</span>
        </div>
        <div style="background-color: #f5f5f5;height: 1px;width: 100%"></div>
        <div v-if="ismyself==true" class="delete" @click="deletereply">
          <span>删除</span>
        </div>
        <div style="background-color: #f5f5f5;height: 0.1rem;width: 100%"></div>
        <div class="cancle" @click="replycancle">
          <span>取消</span>
        </div>
      </div>
    </mt-popup>
    <div class="loadmore-container" ref="myWrapper">
    <div class="loadmore-ul">

    <div v-for="(item,index) in discuss" style="background-color: white;" :key="index">
      <hotheader :commentindex="index" :type="1" :nickname="item.name" :saytime="item.time" :avatarimg="item.head"
                 :place="item.place" :ssshow='item.isRecommend==1' :userType="item.userType" :isTalent="item.isTalent" :pendantType="item.pendantType" :pendantPicUrl="item.pendantPicUrl"></hotheader>
      <commentbody :commentindex="index" :commenttype="null" :commenttext="item.content"
                   :piclength="item.picture.length" :picarray="item.picture" @showImg="popupImg"></commentbody>
    </div>
      <div style="margin-top: 0.2rem">
        <div class="allcomments">
          <div>全部评论<span style="margin-left: 0.2rem">(<span style="color: #fb6856;">{{commentcounts}}</span>)</span></div>
        </div>
        <div style="background-color: white;padding-bottom: 0.95rem;min-height:80vh;">
          <div class="comment" v-for="(items,index) in commentList" :key="index">
            <commentdetailheader :zannum="items.likeNumber" :avaterImg="items.headImg" :name="items.nickName" :time="items.timeStamp" :commentindex="index"
                                   :commentdetailisup="items.isgood" @comentdetailthumb="iscomentdetailthumb" @replycomment="replyother" :userType="items.userType" :isTalent="items.isTalent" :pendantType="items.pendantType" :pendantPicUrl="items.pendantPicUrl"></commentdetailheader>
            <commentbody :atname="items.atName" :commenttype="items.atName" :commenttext="items.content" :piclength="items.picture.length"
                           :picarray="items.picture" @replycomment="replyother" :commentindex="index" @showImg="popupImg"></commentbody>
          </div>

        </div>
      </div>
      </div></div>
      <div v-for="(item,index) in discuss" style="background-color: white;" :key="index">
        <div style="position: fixed;bottom: 0;width: 100%;z-index: 2;height: 0.9rem;">
          <div class="bottom-sep"></div>
          <thumb-up :topiccommentnum="commentcounts" :thumbupnum="item.likes" :commentindex="index" :isup="item.isgood"
                     @thumbup="saythumbup" @commentsvgg="saycomment"></thumb-up>

        </div>
      </div>
       <transition name="fade">
        <div class="modal-img" v-if="popupVisible" @click="popupVisible=false">
          <mt-swipe :auto="100000" style="width: 100%;height: 100vh;position:relative;"
          :continuous="false" 
            :defaultIndex="swiperIndex" :showIndicators="false" >
              <mt-swipe-item v-for="(item,index) in popImg" :key="index" style="height:100vh" >
                <img v-lazy="item" class="swiper-img" />
              </mt-swipe-item>
            </mt-swipe>
          </div>
        </transition>
  </div>
</template>
<script>
import ylheader from "src/components/yl-header.vue";
import hotheader from "src/components/allhot-header.vue";
import commentbody from "src/components/comment-detail-body.vue";
import commentdetailheader from "src/components/commentdetail-header.vue";
import thumbUp from "src/components/thumb-up.vue";
import { Pupup } from "mint-ui";
import api from "src/api/index";
import deletepopup from "src/components/deletepopup.vue";
export default {
  name:"shuodetail",
  data() {
    return {
      swiperIndex:0,
      popupVisible:false,
      popImg:'',
      isuptype: 0,
      isdelete: false,
      isreply: false,
      headertype: this.$route.query.type,
      commentList: [],
      discuss: [],
      commentcounts: "",
      tag: "",
      ismyself: "",
      isme: "",
      showdelete: false,
      mystatus: "",
      hasmore: "",
      page: 1,
      myshenhetype: -1,
      is_r: false,
      hasmore: false,
      rightcollectsvgicon:0,//0未收藏，1已收藏
    };
  },
  mounted() {
    const addclick = {
        id: this.$route.query.saysId,
        type: 2
    };
    this.$util.saveclicknum(addclick);
    this.initSay()
      .then(data => {
        return this.initSaycomments();
      })
      .then(data => {
        return this.initScroll();
      })
      .then(data => {
        this.$nextTick(() => {
          this.myscroll.refresh();
        });
      });
  },
  components: {
    ylheader,
    hotheader,
    commentbody,
    commentdetailheader,
    thumbUp,
    Pupup,
    deletepopup,
  },
  methods: {
    //显示图片
    popupImg(data,index){
      this.swiperIndex = index
      if(typeof data == 'string'){
        data = data.split(',')
      }
       //console.log(data,index)
      this.popImg = data;
      this.popupVisible = true;
      // console.log(this.swiperOne)
      // this.swiperOne.slideTo(index)
    },
    initSay() {
      let p = new Promise((resolve, reject) => {
        const data = {
          page: 1,
          limit: 1,
          saysId: this.$route.query.saysId,
          type:0
        };
        api.Querysay(data).then(res => {
          if (res.success) {
            this.discuss = res.data.list;
            if(res.data.list.length==0){
              this.$toast("该说说已被删除");
              this.$router.go(-1);
              return;
            }
            this.rightcollectsvgicon = res.data.list[0].isCollected;
            this.picAutoOrient(res.data.currPage-1,this.discuss);
             this.$util.getListUrl(this.discuss);
            if (this.discuss[0].userId == localStorage.getItem("userId")) {
              this.isme = true;
            } else {
              this.isme = false;
            }
            if(typeof(this.$route.query.shuoshuoIndex)!="undefined"&&typeof(localStorage.sayStorage)!="undefined"){
              let sayObj = JSON.parse(localStorage.sayStorage);
              sayObj.commentlist[this.$route.query.shuoshuoIndex].commentNumber=this.discuss[0].commentNumber;
              let tempSayObj = JSON.stringify({
                commentlist: sayObj.commentlist,
                totalPage: sayObj.totalPage,
                hasmore: sayObj.hasmore,
                pageone: sayObj.pageone,
                pagetwo: sayObj.pagetwo,
                mypage: sayObj.mypage,
                timeorhot: sayObj.timeorhot
              });
              localStorage.sayStorage = tempSayObj;
            }
            resolve("获取说说数据...");
          } else {
            resolve("获取说说详情失败...");
          }
        });
      });
      return p;
    },
    initSaycomments() {
      let p = new Promise((resolve, reject) => {
        if (this.hasmore) this.page += 1;
        const params = {
          page: this.page,
          limit: 10,
          saysId: this.$route.query.saysId
        };
        api.Querysaycomments(params).then(res => {
          if (res.success) {
            if(!res.data||res.data.list.length==0){
              this.commentcounts=0;
                return;
              }
            this.commentList = [...this.commentList, ...res.data.list];
            this.$util.getListUrl(this.commentList);
            var tempLength = this.commentList.length;
            if (tempLength != 0) {
              this.picAutoOrient(res.data.currPage-1,this.commentList);
            }
            this.commentcounts = res.data.totalCount;
            if (res.data.currPage < res.data.totalPage) {
              this.is_r = false;
              this.hasmore = true;
            } else {
              this.hasmore = false;
            }
            if (this.page > 1) {
              setTimeout(() => {
                this.myscroll.refresh();
              }, 0);
            }
            resolve("获取说说详情...");
          } else {
            resolve("获取说说详情失败...");
          }
        });
      });
      return p;
    },
    //初始化scroll
    initScroll() {
      let p = new Promise((resolve, reject) => {
        let myWrapper = this.$refs.myWrapper;
        let _this = this;
        this.$nextTick(() => {
          localStorage.tempPageHeight = document.getElementsByClassName(
            "loadmore-ul"
          )[0].scrollHeight;
          _this.myscroll = new iScroll(myWrapper, {
            onScrollMove: function() {
              if (
                this.y <= this.wrapperH - this.scroller.clientHeight - 50 &&
                _this.hasmore &&
                _this.is_r == false
              ) {
                _this.is_r = true;
                _this.initSaycomments();
              }
            },
            onScrollEnd: function() {},
            onScrollStart: function() {
              if (
                localStorage.tempPageHeight !=
                document.getElementsByClassName("loadmore-ul")[0].scrollHeight
              ) {
                this.refresh();
                localStorage.tempPageHeight = document.getElementsByClassName(
                  "loadmore-ul"
                )[0].scrollHeight;
              }
            }
          });
          resolve("初始化scroll");
        });
      });
      return p;
    },
    deletetopiccomments() {
      this.showdelete = false;
      if (this.mystatus == "big") {
        if (localStorage.getItem("userId") != this.discuss[0].userId) {
          return;
        }
        const data = {
          saysId: this.discuss[0].saysId
        };
        api.Querydeletesays(data).then(res => {
          if (res.success) {
            this.discuss.pop();
            this.isdelete = false;
            localStorage.turnCount = "";
            this.$router.go(-1);
            //              this.commentList = []
          } else {
            this.$toast("删除失败");
          }
        });
      } else if (this.mystatus == "small") {
        if (
          localStorage.getItem("userId") != this.commentList[this.tag].userId
        ) {
          return;
        }
        const id = {
          commentId: this.commentList[this.tag].commentId
        };
        api.Querydeletesayscomments(id).then(res => {
          if (res.success) {
            this.isreply = false;
            this.commentList.splice(this.tag, 1);
            this.commentcounts -= 1;
          } else {
            this.$toast("删除失败");
          }
        });
      }
    },
    saythumbup(data) {
      const params = {
        saysId: this.discuss[data.commentindex].saysId,
        createSaysUserId: this.discuss[data.commentindex].userId
      };
      if (this.discuss[data.commentindex].isgood == 0) {
        api.Querysaythumbup(params).then(res => {
          if (res.success) {
            this.$util.saveFootPrint({actType:9,typeValue:this.$route.query.saysId});//用户轨迹
            this.discuss[data.commentindex].isgood = 1;
            this.discuss[data.commentindex].likes = res.data;
            let sayObj = JSON.parse(localStorage.sayStorage);
            sayObj.commentlist[this.$route.query.shuoshuoIndex].isgood = 1;
            sayObj.commentlist[this.$route.query.shuoshuoIndex].likes =
              res.data;
            let tempSayObj = JSON.stringify({
              commentlist: sayObj.commentlist,
              totalPage: sayObj.totalPage,
              hasmore: sayObj.hasmore,
              pageone: sayObj.pageone,
              pagetwo: sayObj.pagetwo,
              mypage: sayObj.mypage,
              timeorhot: sayObj.timeorhot
            });
            localStorage.sayStorage = tempSayObj;
          }
        });
      } else if (this.discuss[data.commentindex].isgood == 1) {
        api.Querysaycanclethumbup(params).then(res => {
          if (res.success) {
            this.discuss[data.commentindex].isgood = 0;
            this.discuss[data.commentindex].likes = res.data;
            let sayObj = JSON.parse(localStorage.sayStorage);
            sayObj.commentlist[this.$route.query.shuoshuoIndex].likes =
              res.data;
            sayObj.commentlist[this.$route.query.shuoshuoIndex].isgood = 0;
            let tempSayObj = JSON.stringify({
              commentlist: sayObj.commentlist,
              totalPage: sayObj.totalPage,
              hasmore: sayObj.hasmore,
              pageone: sayObj.pageone,
              pagetwo: sayObj.pagetwo,
              mypage: sayObj.mypage,
              timeorhot: sayObj.timeorhot
            });
            localStorage.sayStorage = tempSayObj;
          }
        });
      }
    },
    saycomment(data) {
      this.$router.push({
        path: "/publishshuoshuo",
        query: {
          saysId: this.discuss[data.commentindex].saysId,
          saysUserId: this.discuss[0].userId,
          shuoshuoIndex: this.$route.query.shuoshuoIndex
        }
      });
    },
    iscomentdetailthumb(data) {
      const likeparam = {
        commentId: this.commentList[data.commentindex].commentId,
        createSaysUserId: this.commentList[data.commentindex].userId
      };
      const canclelikeparam = {
        commentId: this.commentList[data.commentindex].commentId
      };
      if (this.commentList[data.commentindex].isgood == 0) {
        api.Querysaycommentthumbup(likeparam).then(res => {
          if (res.success) {
            this.$util.saveFootPrint({actType:10,typeValue:this.commentList[data.commentindex].commentId});//用户轨迹
            this.commentList[data.commentindex].isgood = 1;
            this.commentList[data.commentindex].likeNumber = res.data;
          } else {
            this.$toast("点赞失败");
          }
        });
      } else if (this.commentList[data.commentindex].isgood == 1) {
        api.Querycanclesaycommentthumbup(canclelikeparam).then(res => {
          if (res.success) {
            this.commentList[data.commentindex].isgood = 0;
            this.commentList[data.commentindex].likeNumber = res.data;
          } else {
            this.$toast("取消点赞失败");
          }
        });
      }
    },
    deletemycomment() {
      const data = {
        type: "2",
        id: this.$route.query.saysId
      };
      api.Queryshenhe(data).then(res => {
        if (res.success) {
          if (res.data == "1") {
            this.myshenhetype = 2;
          } else if (res.data == "0") {
            this.myshenhetype = 1;
          }
        }
      });
      this.isdelete = true;
    },
    deletemycomments() {
      this.isdelete = false;
      this.showdelete = true;
      this.mystatus = "big";
    },
    canaledeteletopiccomments() {
      this.showdelete = false;
    },
    iscancle() {
      this.isdelete = false;
    },
    replyother(data) {
      if (
        localStorage.getItem("userId") ==
        this.commentList[data.commentindex].userId
      ) {
        this.ismyself = true;
      } else {
        this.ismyself = false;
      }
      this.isreply = true;
      this.tag = data.commentindex;
      if(this.ismyself){
        const mydata = {
          type: "3",
          id: this.commentList[data.commentindex].commentId
        };
        api.Queryshenhe(mydata).then(res => {
          if (res.success) {
            if (res.data == "1") {
              this.myshenhetype = 2;
            } else if (res.data == "0") {
              this.myshenhetype = 1;
            }
          }
        });
      }
    },

    replycom() {
      this.$router.push({
        path: "/publishshuoshuo",
        query: {
          saysId: this.commentList[this.tag].saysId,
          saysUserId: this.discuss[0].userId,
          replyId: this.commentList[this.tag].userId,
          parentId: this.commentList[this.tag].commentId
        }
      });
    },
    deletereply() {
      this.isreply = false;
      this.showdelete = true;
      this.mystatus = "small";
    },
    replycancle() {
      this.isreply = false;
    },
    //图片自动旋转参数
    picAutoOrient(page,data) {
      for (var m = 10*page; m < data.length; m++) {
        if (data[m].picture.length != 0) {
          for (var n = 0; n < data[m].picture.length; n++) {
            data[m].picture[n].src =
              data[m].picture[n].src + "?imageMogr2/auto-orient";
          }
        }
      }
    },
    iscollectevent(data){
      if(this.rightcollectsvgicon==0){
        const params = {type:1,itemId:this.$route.query.saysId};
        api.addCollection(params).then(res=>{
            if(res.success){
                this.$util.saveFootPrint({actType:14,typeValue:this.$route.query.saysId});//用户轨迹
                this.rightcollectsvgicon=1;
                this.$toast("收藏成功");
            }
        }) 
      }else if(this.rightcollectsvgicon==1){
        const params = {type:1,itemId:this.$route.query.saysId};
        api.cancelCollection(params).then(res=>{
            if(res.success){
                this.rightcollectsvgicon=0;
                this.$toast("取消收藏成功");
            }
        })  
      }
    },
    deleteshow(data){
        this.showdelete=data;
    },
  }
};
</script>
<style lang="less" scoped>
.modal-img{
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,.5);
  position: fixed;
  top:0;
  left: 0;
  z-index: 9999;
  img{
    width: 80%;
    position: absolute;
    top:50%;
    left: 10%;
    transform: translateY(-50%);
  }
}
.allcomments {
  width: 100%;
  height: 0.89rem;
  background-color: white;
  line-height: 0.88rem;
  font-family: "PingFangSC Regular";
  font-size: 0.3rem;
  color: #666666;
  div {
    margin-left: 0.3rem;
    width: 6.9rem;
    height: 0.88;
    border-bottom: 1px solid #e6e6e6;
  }
}
.bottom-sep {
  width: 6.9rem;
  margin-left: 0.3rem;
  height: 1px;
  background-color: #e6e6e6;
}
.delete {
  height: 0.9rem;
  line-height: 0.9rem;
  font-size: 0.3rem;
  color: #333333;
  font-family: "PingFangSC Regular";
  width: 100%;
  text-align: center;
}
.cancle {
  height: 0.9rem;
  width: 100%;
  text-align: center;
  line-height: 0.9rem;
  font-size: 0.3rem;
  color: #de4b4e;
  font-family: "PingFangSC Regular";
}
.loadmore-container {
  height: 95vh;
  overflow: hidden;
  margin: 0 auto;
}
.loadmore-ul {
  padding-bottom: 1.2rem;
  list-style: none;
}
</style>
